package com.sdhs.costcontrol.service.impl;

import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.sdhs.common.core.domain.event.ProcessEvent;
import com.sdhs.common.enums.BusinessStatusEnum;
import com.sdhs.common.enums.OtherEnum;
import com.sdhs.common.utils.StringUtils;
import com.sdhs.file.utils.ManageListUtil;
import com.sdhs.listmanage.service.IGcManageListService;
import com.sdhs.workflow.domain.vo.WfDefinitionConfigVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sdhs.businessfile.domain.BusinessFile;
import com.sdhs.businessfile.service.IBusinessFileService;
import com.sdhs.common.enums.BusinessTypeEnum;
import com.sdhs.common.utils.DateUtils;
import com.sdhs.common.utils.SecurityUtils;
import com.sdhs.costcontrol.domain.GcControlChangeManageList;
import com.sdhs.costcontrol.domain.GcControlChangeManagement;
import com.sdhs.costcontrol.mapper.GcControlChangeManageListMapper;
import com.sdhs.costcontrol.mapper.GcControlChangeManagementMapper;
import com.sdhs.costcontrol.service.IGcControlChangeManagementService;
import com.sdhs.listmanage.domain.entity.GcManageList;
import com.sdhs.listmanage.mapper.GcManageListMapper;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;

/**
 * 变更管理Service业务层处理
 *
 * @author wanglei
 * @date 2025-03-12
 */
@Service
public class GcControlChangeManagementServiceImpl implements IGcControlChangeManagementService {
    @Autowired
    private GcControlChangeManagementMapper gcControlChangeManagementMapper;

    @Autowired
    private IBusinessFileService businessFileService;

    @Autowired
    private GcControlChangeManageListMapper gcControlChangeManageListMapper;

    @Autowired
    private GcManageListMapper gcManageListMapper;


    @Autowired
    private IGcManageListService gcManageListService;
    /**
     * 查询变更管理
     *
     * @param id 变更管理主键
     * @return 变更管理
     */
    @Override
    public GcControlChangeManagement selectGcControlChangeManagementById(Long id) {
        GcControlChangeManagement controlChangeManagement = gcControlChangeManagementMapper.selectGcControlChangeManagementById(id);
        List<BusinessFile> fileList = businessFileService.listByBusinessTypeAndId(BusinessTypeEnum.GC_CONTROL_CHANGE_MANAGEMENT.getCode(), String.valueOf(id));
        controlChangeManagement.setFileList(fileList);
        /*根据主键查询变更清单列表*/
        List<GcControlChangeManageList> gcControlChangeManageLists = gcControlChangeManageListMapper.selectGcControlChangeManageByIdList(id);
        controlChangeManagement.setGcControlPlanList(gcControlChangeManageLists);
        return controlChangeManagement;
    }

    /**
     * 查询变更管理列表
     *
     * @param gcControlChangeManagement 变更管理
     * @return 变更管理
     */
    @Override
    public List<GcControlChangeManagement> selectGcControlChangeManagementList(GcControlChangeManagement gcControlChangeManagement) {
        return gcControlChangeManagementMapper.selectGcControlChangeManagementList(gcControlChangeManagement);
    }

    /**
     * 新增变更管理
     *
     * @param gcControlChangeManagement 变更管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public GcControlChangeManagement insertGcControlChangeManagement(GcControlChangeManagement gcControlChangeManagement) {
        gcControlChangeManagement.setCreater(SecurityUtils.getUsername());
        gcControlChangeManagement.setCreateTime(DateUtils.getNowDate());
        gcControlChangeManagement.setApprovalStatus(BusinessStatusEnum.DRAFT.getStatusValue());
        gcControlChangeManagementMapper.insertGcControlChangeManagement(gcControlChangeManagement);
        handler(gcControlChangeManagement.getId(), gcControlChangeManagement);
        return gcControlChangeManagement;
    }

    /**
     * 修改变更管理
     *
     * @param gcControlChangeManagement 变更管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateGcControlChangeManagement(GcControlChangeManagement gcControlChangeManagement) {
        gcControlChangeManagement.setUpdater(SecurityUtils.getUsername());
        gcControlChangeManagement.setUpdateTime(DateUtils.getNowDate());
        int result = gcControlChangeManagementMapper.updateGcControlChangeManagement(gcControlChangeManagement);
        handler(gcControlChangeManagement.getId(), gcControlChangeManagement);
        return result;
    }

    /**
     * 批量删除变更管理
     *
     * @param ids 需要删除的变更管理主键
     * @return 结果
     */
    @Override
    public int deleteGcControlChangeManagementByIds(Long[] ids) {
        return gcControlChangeManagementMapper.deleteGcControlChangeManagementByIds(ids);
    }

    /**
     * 删除变更管理信息
     *
     * @param id 变更管理主键
     * @return 结果
     */
    @Override
    public int deleteGcControlChangeManagementById(Long id) {
        return gcControlChangeManagementMapper.deleteGcControlChangeManagementById(id);
    }

    /**
     * 保存变更管理清单数据
     * 1-变更管理清单管理
     * 1-附件
     */
    public void handler(Long id, GcControlChangeManagement gcControlChangeManagement) {
        List<GcControlChangeManageList> gcControlChangeManageList = gcControlChangeManagement.getGcControlPlanList();
        List<GcControlChangeManageList> gcControlChangeManageLists = gcControlChangeManageListMapper.selectGcControlChangeManageByIdList(id);

        if (CollectionUtil.isNotEmpty(gcControlChangeManageLists)){
            gcControlChangeManageListMapper.deleteGcControlChangeManageListById(id);
        }
        for (int i = 0;i<gcControlChangeManageList.size();i++){
            GcControlChangeManageList gcControlManageList = gcControlChangeManageList.get(i);
            gcControlManageList.setProjectId(gcControlChangeManagement.getProjectId());
            gcControlManageList.setChangeId(id);
            /*gcControlManageList.setId(null); //回头删除这一行使用下面的方法*/
            /*如果是添加数据的话将manageId设置为id--屏蔽开始*/
            gcControlManageList.setId(IdWorker.getId());
            if (gcControlManageList.getChangeType()!=null && gcControlManageList.getChangeType().equals(OtherEnum.ADD_ENUM.getCode())){
                gcControlManageList.setManageId(gcControlManageList.getId());
            }
            /*屏蔽结束到这个位置*/
            gcControlChangeManageListMapper.insertGcControlChangeManageList(gcControlManageList);
        }
        businessFileService.saveFileBatch(BusinessTypeEnum.GC_CONTROL_CHANGE_MANAGEMENT.getCode(), String.valueOf(id), gcControlChangeManagement.getFileList());
    }

    /**
     * 审批完成后修改清单管理
     *     @Transactional(rollbackFor = Exception.class)
     *     调用这个接口的时候使用上面的注解写成异步的
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateHandler(GcControlChangeManagement gcControlChangeManagement) {
        if (gcControlChangeManagement == null || gcControlChangeManagement.getId() == null) {
            return;
        }
            /*根据变更id查询变更清单数据*/
        List<GcControlChangeManageList> changeManageLists = gcControlChangeManageListMapper
                .selectGcControlChangeManageByIdList(gcControlChangeManagement.getId());

        for (GcControlChangeManageList changeManageItem : changeManageLists) {
            GcManageList manageListItem = BeanUtil.toBean(changeManageItem, GcManageList.class);

            if (manageListItem == null) {
                continue;
            }
            /*如果单位是空的话或者数量是0或者空的话不走计算*/
            if(manageListItem.getQuantity()!=null && !Objects.equals(manageListItem.getQuantity(), "0") &&
            manageListItem.getSalePrice()!=null && !Objects.equals(manageListItem.getSalePrice(), "0") &&
            manageListItem.getDevicePrice()!=null && !Objects.equals(manageListItem.getDevicePrice(), "0") &&
            manageListItem.getConstructionPrice()!=null && !Objects.equals(manageListItem.getConstructionPrice(), "0") &&
            manageListItem.getOtherPrice()!=null && !Objects.equals(manageListItem.getOtherPrice(), "0") &&
            manageListItem.getUnit()!=null){
                /*调用计算方法*/
                gcManageListService.manageListCompute(manageListItem);
            }


            /*下面是新的方法，屏蔽的是之前的方法*/
            if (changeManageItem.getChangeType()!=null && changeManageItem.getChangeType().equals(OtherEnum.ADD_ENUM.getCode())) {
                manageListItem.setId(manageListItem.getManageId());
                manageListItem.setRemark("新增采购");
                gcManageListMapper.insertGcManageList(manageListItem);
            } else if (changeManageItem.getChangeType()!=null && changeManageItem.getChangeType().equals(OtherEnum.UPDATE_ENUM.getCode())){
                manageListItem.setId(manageListItem.getManageId());
                gcManageListMapper.updateGcManageList(manageListItem);
            } else if (changeManageItem.getChangeType()!=null && changeManageItem.getChangeType().equals(OtherEnum.DELETE_ENUM.getCode())){
                manageListItem.setId(changeManageItem.getManageId());
                manageListItem.setIsDelete("1");
                gcManageListMapper.updateGcManageList(manageListItem);
            }
        }
        //回头删除下面的方法使用上面的方法 --屏蔽开始位置
       /* for (GcControlChangeManageList changeManageItem : changeManageLists) {
            GcManageList manageListItem = BeanUtil.toBean(changeManageItem, GcManageList.class);

            if (manageListItem == null) {
                continue;
            }
            *//*获取王磊计算方法*//*
            gcManageListService.manageListCompute(manageListItem);
            if (BusinessTypeEnum.GC_CONTROL_CHANGE.getCode().equals(manageListItem.getRemark())) {
                manageListItem.setId(manageListItem.getManageId());
                manageListItem.setRemark("新增采购");
                gcManageListMapper.updateGcManageList(manageListItem);
            } else {
                manageListItem.setId(manageListItem.getManageId());
                gcManageListMapper.updateGcManageList(manageListItem);
            }
        }
        GcManageList gcManageList = new GcManageList();
        gcManageList.setProjectId(gcControlChangeManagement.getProjectId());
        gcManageList.setUpdater("gcControlChangeDel");
        List<GcManageList> gcManageLists = gcManageListMapper.selectGcManageListList(gcManageList);
        if (CollectionUtil.isNotEmpty(gcManageLists)){
            for (GcManageList gcManageListItem : gcManageLists){
                gcManageListItem.setIsDelete("1");
                gcManageListMapper.updateGcManageList(gcManageListItem);
            }
        }*/
        /*屏蔽结束到这个位置*/
    }


    /**
     * 总体流程监听(例如: 提交 退回 撤销 终止 作废等)
     * 正常使用只需#processEvent.key=='leave1'
     * 示例为了方便则使用startsWith匹配了全部示例key
     *
     * @param processEvent 参数
     */
    @org.springframework.context.event.EventListener(condition = "#processEvent.key.startsWith('project_changes')")
    public void processHandler(ProcessEvent processEvent) {

            // 已完成（已通过）
            if (BusinessStatusEnum.FINISH.getStatus().equals(processEvent.getStatus())) {
                 String businessKey = processEvent.getBusinessKey();
                 GcControlChangeManagement gcControlChangeManagement = gcControlChangeManagementMapper.selectGcControlChangeManagementByInstanceId(businessKey);
                updateHandler(gcControlChangeManagement);
                GcManageList gcManageList = new GcManageList();
                gcManageList.setProjectId(gcControlChangeManagement.getProjectId());
                gcManageList.setProcurementType("0");
                List<GcManageList> gcManageLists = gcManageListMapper.selectGcManageListList(gcManageList);
                /*审批结束之后计算清单--标前利润率*/
                ManageListUtil.UpdateMeasurement(gcControlChangeManagement.getProjectId(),gcManageLists);
            }

    }
}
